import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';

export const useUploadStore = defineStore('uploads', () => {
  // 从 localStorage 加载持久化的上传数据
  const storedData = localStorage.getItem('uploads');
  const storedUploads = storedData ? JSON.parse(storedData) : [];
  
  // 上传任务列表（响应式）
  const uploads = ref(storedUploads);
  
  // 获取特定上传任务
  const getUpload = (id) => {
    return uploads.value.find(u => u.id === id);
  };
  
  // 添加或更新上传任务
  const addUpload = (uploadTask) => {
    const existingIndex = uploads.value.findIndex(u => u.id === uploadTask.id);
    
    if (existingIndex !== -1) {
      // 更新现有任务
      uploads.value[existingIndex] = {
        ...uploads.value[existingIndex],
        ...uploadTask,
        // 保留进度和速度
        uploadPercentage: uploadTask.uploadPercentage || uploads.value[existingIndex].uploadPercentage,
        uploadSpeed: uploadTask.uploadSpeed || uploads.value[existingIndex].uploadSpeed,
        // 保留分片相关数据
        chunkList: uploadTask.chunkList || uploads.value[existingIndex].chunkList || [],
        totalChunks: uploadTask.totalChunks || uploads.value[existingIndex].totalChunks || 0,
        // 重置暂停状态
        isPaused: false,
        status: 'uploading',
        uploadingStop: false
      };
      return uploads.value[existingIndex];
    }
    
    // 创建新任务
    const newUpload = {
      ...uploadTask,
      uploadPercentage: 0,
      uploadSpeed: '0 KB/s',
      isPaused: false,
      status: 'uploading',
      chunkList: [], // 已上传的分片索引列表
      totalChunks: 0, // 总分片数
      uploadingStop: false // 上传停止标记
    };
    
    uploads.value.push(newUpload);
    return newUpload;
  };
  
  // 添加已上传的分片到任务
  const addChunk = (id, chunkIndex) => {
    const upload = getUpload(id);
    console.log(upload);
    if (upload) {
      if (!upload.chunkList.includes(chunkIndex)) {
        upload.chunkList.push(chunkIndex);
        
        // 自动更新进度
        if (upload.totalChunks > 0) {
          const progress = Math.min(100, Math.round((upload.chunkList.length / upload.totalChunks) * 100));
          upload.uploadPercentage = progress;
          
          // 检查是否完成
          if (progress >= 100) {
            upload.status = 'completed';
          }
        }
      }
    }
    return upload;
  };
  
  // 更新上传进度
  const updateProgress = (id, progress, speed) => {
    const upload = getUpload(id);
    if (upload) {
      upload.uploadPercentage = Math.min(progress, 100);
      upload.uploadSpeed = speed || upload.uploadSpeed;
      
      // 当进度达到100%时标记为完成
      if (progress >= 100) {
        upload.status = 'completed';
      }
    }
  };
  
  // 暂停上传
  const pauseUpload = (id) => {
    const upload = getUpload(id);
    if (upload) {
      upload.isPaused = true;
      upload.status = 'paused';
      upload.uploadingStop = true;
    }
  };
  
  // 继续上传
  const resumeUpload = (id) => {
    const upload = getUpload(id);
    if (upload) {
      upload.isPaused = false;
      upload.status = 'uploading';
      upload.uploadingStop = false;
    }
  };
  
  // 设置上传停止状态
  const setUploadingStop = (id, stop) => {
    const upload = getUpload(id);
    if (upload) {
      upload.uploadingStop = stop;
    }
  };
  
  // 重试上传
  const retryUpload = (id) => {
    const upload = getUpload(id);
    if (upload) {
      upload.status = 'uploading';
      upload.uploadPercentage = 0;
      upload.isPaused = false;
      upload.needUpload = true;
      upload.chunkList = []; // 清空已上传分片列表
      upload.uploadingStop = false;
    }
    return upload;
  };
  
  // 标记上传完成
  const completeUpload = (id) => {
    const upload = getUpload(id);
    if (upload) {
      upload.status = 'completed';
      upload.uploadPercentage = 100;
      upload.isPaused = false;
      upload.uploadingStop = false;
    }
  };
  
  // 标记上传出错
  const setError = (id) => {
    const upload = getUpload(id);
    if (upload) {
      upload.status = 'error';
      upload.uploadingStop = true;
    }
  };
  
  // 移除上传任务
  const removeUpload = (id) => {
    const index = uploads.value.findIndex(u => u.id === id);
    if (index !== -1) {
      uploads.value.splice(index, 1);
    }
  };
  
  // 设置总分片数
  const setTotalChunks = (id, totalChunks) => {
    const upload = getUpload(id);
    if (upload) {
      upload.totalChunks = totalChunks;
    }
  };
  
  // 计算属性：所有上传任务
  const allUploads = computed(() => {
    return uploads.value;
  });
  
  // 计算属性：活动中的上传任务（上传中或已暂停）
  const activeUploads = computed(() => {
    return uploads.value.filter(u => u.status === 'uploading' || u.status === 'paused');
  });
  
  // 计算属性：已完成的上传任务
  const completedUploads = computed(() => {
    return uploads.value.filter(u => u.status === 'completed');
  });
  
  // 计算属性：失败的上传任务
  const failedUploads = computed(() => {
    return uploads.value.filter(u => u.status === 'error');
  });

  // 监听上传任务变化，持久化到 localStorage
  watch(uploads, (newValue) => {
    // 排除 File 对象（不可序列化）
    const serializable = newValue.map(u => {
      const { file, ...rest } = u;
      return rest;
    });
    
    localStorage.setItem('uploads', JSON.stringify(serializable));
  }, { deep: true });
  
  return {
    // 状态
    uploads,
    
    // 计算属性
    allUploads,
    activeUploads,
    completedUploads,
    failedUploads,
    
    // 方法
    getUpload,
    addUpload,
    addChunk,
    updateProgress,
    pauseUpload,
    resumeUpload,
    setUploadingStop,
    retryUpload,
    completeUpload,
    setError,
    removeUpload,
    setTotalChunks
  };
});